package com.gcu.common.skin

import android.content.Context
import android.content.res.Configuration
import com.gcu.common.R
import com.gcu.common.navigation.AppApi
import com.gcu.common.utils.SPUtil
import com.qmuiteam.qmui.skin.QMUISkinManager

/**
 * Gcu skin manager
 * APP全局皮肤管理类
 * @constructor Create empty Gcu skin manager
 */
class GcuSkinManager {

    companion object {
        private const val SKIN_PINK = 1
        private const val SKIN_BLUE = 2
        private const val SKIN_WHITE = 3

        private var mSkinManager: GcuSkinManager? = null

        fun init(context: Context) {
            if (mSkinManager == null) {
                mSkinManager = GcuSkinManager()
                mSkinManager?.init(context)
            }
        }

        fun getDefault(): GcuSkinManager? {
            return mSkinManager
        }
    }

    private fun init(context: Context) {
        val skinManager = QMUISkinManager.defaultInstance(context)
        skinManager.addSkin(SKIN_PINK, R.style.AppTheme)
        skinManager.addSkin(SKIN_BLUE, R.style.app_skin_1)
        skinManager.addSkin(SKIN_WHITE, R.style.app_skin_2)

        //判断是否为黑夜模式
        val isDarkMode =
            (context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
        val storeSkinIndex = getSkinIndex()
        if (isDarkMode && storeSkinIndex != SKIN_WHITE) {
            skinManager.changeSkin(SKIN_WHITE)
        } else if (!isDarkMode && storeSkinIndex == SKIN_BLUE) {
            skinManager.changeSkin(SKIN_BLUE)
        } else {
            skinManager.changeSkin(SKIN_PINK)
        }
    }

    /**
     * 换肤
     * @param pos Int
     * @param context Context
     */
    fun changeSkin(pos: Int, context: Context) {
        QMUISkinManager.defaultInstance(context.applicationContext).changeSkin(pos)

    }

    /**
     * 设置app版本号
     * @param version Int
     */
    fun setVersionCode(version: Int) {
        SPUtil.putInt(AppApi.SPKey.APP_VERSION_CODE, version)
    }

    /**
     * 存储使用皮肤的下标
     * @param pos Int
     */
    fun setSkinPos(pos: Int) {
        SPUtil.putInt(AppApi.SPKey.SKIN_POSITION, pos)
    }

    /**
     * 获取存储使用的皮肤下标
     * @return Int
     */
    fun getSkinIndex(): Int {
        return SPUtil.getInt(AppApi.SPKey.SKIN_POSITION)
    }

}